<template>
  <div class="wrapper">
    <!--顶部栏-->
    <header>
      <p>管理员登录</p>
    </header>
    <!-- logo-->
    <div class="logo">
      <i class="fa-solid fa-user-shield fa-3x"></i>
    </div>

    <!-- 登录表单-->
    <div class="login">
      <ul class="form-box">
        <li>
          <div class="title">管理员账号：</div>
          <div class="content">
            <input type="text" v-model="adminId" placeholder="请输入管理员账号" @keyup.enter="handleAdminLogin"/>
          </div>
        </li>
        <li>
          <div class="title">密码：</div>
          <div class="content">
            <input type="password" v-model="password" placeholder="请输入密码" @keyup.enter="handleAdminLogin"/>
          </div>
        </li>
        <li class="remember-me">
          <div class="content">
            <label class="checkbox-container">
              <input type="checkbox" v-model="rememberMe" @keyup.enter="handleAdminLogin"/>
              <span class="checkmark"></span>
              记住我
            </label>
          </div>
        </li>
      </ul>

      <!-- 错误信息提示 -->
      <div v-if="errorMessage" class="error-message">
        <p>{{ errorMessage }}</p>
      </div>

      <!-- 登录按钮 -->
      <div class="button-login">
        <button @click="handleAdminLogin" :disabled="loading">
          {{ loading ? '登录中...' : '管理员登录' }}
        </button>
      </div>

      <!-- 返回普通登录按钮 -->
      <div class="button-back">
        <button @click="handleBackToNormalLogin">返回普通登录</button>
      </div>
    </div>

    <!--  底部菜单-->
    <Footer></Footer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from  '@/stores/auth'
import { authAPI } from '@/api/auth.js'
import { userAPI } from '@/api/user.js'
import Footer from "@/components/Footer.vue";

// 响应式数据
const adminId = ref('')
const password = ref('')
const rememberMe = ref(false)
const loading = ref(false)
const errorMessage = ref('')
const router = useRouter()
const authStore = useAuthStore()
const ROLES = {
  USER: 'USER',
  BUSINESS: 'BUSINESS',
  ADMIN: 'ADMIN'
}
// 权限验证
const validateAdminPermission = (userAuthorities) => {
  if (!userAuthorities || !Array.isArray(userAuthorities)) {
    return false
  }

  // 检查是否包含管理员权限
  return userAuthorities.some(auth => {
    return auth.name && (auth.name === 'ADMIN')
  })
}

// 处理管理员登录
const handleAdminLogin = async () => {
  // 重置错误信息
  errorMessage.value = ''

  // 表单验证
  if (!String(adminId.value).trim()) {
    errorMessage.value = '请输入管理员账号'
    return
  }

  if (!String(password.value).trim()) {
    errorMessage.value = '请输入密码'
    return
  }

  loading.value = true

  try {
    // 发送登录请求获取token
    const loginCredentials = {
      username: adminId.value,
      password: password.value,
      rememberMe: rememberMe.value
    }

    const loginResponse = await authAPI.login(loginCredentials)

    if (!loginResponse.data || !loginResponse.data.id_token) {
      throw new Error(loginResponse.message || '登录失败，未获取到token')
    }

    // 保存登录信息到store
    const authResult = await authStore.login(loginResponse, loginCredentials)

    // 使用token获取当前用户信息（包含权限信息）
    const userResponse = await userAPI.getActualUser()

    if (!userResponse.data) {
      throw new Error('获取用户信息失败')
    }

    // 验证用户是否具有管理员权限
    const userAuthorities = userResponse.data.authorities
    const isAdmin = validateAdminPermission(userAuthorities)

    if (!isAdmin) {
      throw new Error('您没有管理员权限，无法登录管理员系统')
    }

    if (!authResult.success) {
      throw new Error(authResult.message || '登录信息保存失败')
    }

    // 登录成功，跳转到管理员页面
    console.log('管理员登录成功:', userResponse.data)
    const userRole = ROLES.ADMIN
    sessionStorage.setItem('userRole', userRole)
    // 跳转到管理员后台页面
    router.push('/admin')

  } catch (error) {
    console.error('管理员登录失败:', error)
    errorMessage.value = error.message || '管理员登录失败，请检查账号密码'

    // 登录失败时清理token
    authStore.logout()
  } finally {
    loading.value = false
  }
}

// 返回普通登录页面
const handleBackToNormalLogin = () => {
  router.push('/login')
}

// 页面加载时检查是否有记住的管理员账号
onMounted(() => {
  const savedAdminId = sessionStorage.getItem('savedAdminId')
  if (savedAdminId) {
    adminId.value = savedAdminId
    rememberMe.value = true
  }

  // 检查是否已经登录
  const token = sessionStorage.getItem('token')
  const isLoggedIn = !!token

  if (isLoggedIn) {
    console.log('检测到已登录用户访问管理员登录页')

    // 如果是已登录用户，直接跳转到对应页面
    const redirect = router.currentRoute.value.query.redirect
    if (redirect && redirect !== '/admin-login') {
      router.push(redirect)
    } else {
      router.push('/admin')
    }
  }
})
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

header p {
  font-size: 1.5rem;
  font-weight: 600;
  letter-spacing: 1px;
}

/****************** logo部分 ******************/
.logo {
  flex: 0.15;
  margin-top: 12vw;
  display: flex;
  justify-content: center;
  align-items: center;
}

.logo i {
  color: #ff6b6b;
}

/****************** 表单部分 ******************/
.login {
  flex:0.5;
}

.login .form-box {
  width: 100%;
  margin-top: 6vw;
}

.login .form-box li {
  box-sizing: border-box;
  padding: 4vw 3vw 0 3vw;
  display: flex;
  align-items: center;
}

.login .form-box li .title {
  flex: 0 0 30vw;
  font-size: 4vw;
  font-weight: 800;
  color: #666;
}

.login .form-box li .content {
  flex: 1;
}

.login .form-box li .content input {
  border: gray 0.5px solid;
  border-radius: 8px;
  outline: none;
  height: 8vw;
  font-size: 4vw;
  padding: 0 3vw;
}

.login .form-box li .content input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  outline: none;
}

.remember-me {
  margin-top: 2vw;
}

.checkbox-container {
  display: flex;
  align-items: center;
  justify-content: right;
  cursor: pointer;
  font-size: 3.8vw;
  color: #666;
  user-select: none;
}

.checkbox-container input {
  display: none;
}

.checkmark {
  width: 4vw;
  height: 4vw;
  border: 2px solid #ddd;
  border-radius: 3px;
  margin-right: 2vw;
  position: relative;
  transition: all 0.3s ease;
}

.checkbox-container input:checked + .checkmark {
  background-color: #0097ff;
  border-color: #0097ff;
}

.checkbox-container input:checked + .checkmark::after {
  content: '';
  position: absolute;
  left: 1vw;
  top: 0.2vw;
  width: 1vw;
  height: 2vw;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

/****************** 错误信息提示 ******************/
.error-message {
  text-align: center;
  padding: 2vw 3vw;
  margin-top: 2vw;
}

.error-message p {
  font-size: 3.5vw;
  color: #ff6b6b;
  background-color: #fff5f5;
  padding: 2vw;
  border-radius: 8px;
  border-left: 4px solid #ff6b6b;
}

/****************** 登录按钮 ******************/
.login .button-login {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw 3vw 0 3vw;
}

.login .button-login button {
  width: 100%;
  height: 10vw;
  font-size: 3.8vw;
  font-weight: 700;
  color: #fff;
  background-color: #ff6b6b; /* 管理员登录按钮使用特殊颜色 */
  border-radius: 4px;
  border: none;
  outline: none;
  cursor: pointer;
}

.login .button-login button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.login .button-login button:hover:not(:disabled) {
  background-color: #ff5252;
}

/****************** 返回按钮 ******************/
.login .button-back {
  width: 100%;
  box-sizing: border-box;
  padding: 3vw 3vw 0 3vw;
}

.login .button-back button {
  width: 100%;
  height: 8vw;
  font-size: 3.5vw;
  font-weight: 600;
  color: #666;
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
  cursor: pointer;
}

.login .button-back button:hover {
  background-color: #e9ecef;
  border-color: #adb5bd;
}

/****************** 底部菜单部分 ******************/
.wrapper .footer {
  width: 100%;
  height: 14vw;
  border-top: solid 1px #ddd;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.wrapper .footer li {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
  user-select: none;
  cursor: pointer;
}

.wrapper .footer li p {
  font-size: 2.8vw;
}

.wrapper .footer li i {
  font-size: 5vw;
}
</style>